package com.peiwangroup.orderservice.controller;

import com.peiwangroup.orderservice.dto.OrderDTO;
import com.peiwangroup.orderservice.repository.OrderRepository;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.crypto.SecretKey;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @Autowired
    private OrderRepository orderRepository;

    @Value("${jwt.secret}")
    private String jwtSecret;

    @GetMapping("/date/{date}")
    public List<OrderDTO> getOrdersByDate(
            @PathVariable String date,
            @RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader) throws Exception {
        Claims claims = getClaimsFromToken(authHeader);
        String username = claims.getSubject();
        String permission = claims.get("permission", String.class);
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parsedDate = dateFormat.parse(date);
        
        if ("admin".equals(permission)) {
            return orderRepository.findByDate(parsedDate);
        } else {
            return orderRepository.findByDateAndUsername(parsedDate, username);
        }
    }

    @GetMapping("/month/{year}/{month}")
    public List<OrderDTO> getOrdersByMonth(
            @PathVariable int year,
            @PathVariable int month,
            @RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader) {
        Claims claims = getClaimsFromToken(authHeader);
        String username = claims.getSubject();
        String permission = claims.get("permission", String.class);
        
        if ("admin".equals(permission)) {
            return orderRepository.findByYearAndMonth(year, month);
        } else {
            return orderRepository.findByYearAndMonthAndUsername(year, month, username);
        }
    }

    @GetMapping("/range")
    public List<OrderDTO> getOrdersByDateRange(
            @RequestParam @DateTimeFormat(pattern="yyyy-MM-dd") Date start,
            @RequestParam @DateTimeFormat(pattern="yyyy-MM-dd") Date end,
            @RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader) {
        Claims claims = getClaimsFromToken(authHeader);
        String username = claims.getSubject();
        String permission = claims.get("permission", String.class);
        
        if ("admin".equals(permission)) {
            return orderRepository.findByDateBetween(start, end);
        } else {
            return orderRepository.findByDateBetweenAndUsername(start, end, username);
        }
    }

    private Claims getClaimsFromToken(String authHeader) {
        String token = authHeader.substring(7); // 去掉"Bearer "前缀
        SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}